//
//  FavoriteViewController.m
//  LiveDailyNews
//
//  Created by smu on 11-7-19.
//  Copyright 2011年 duk. All rights reserved.
//

#import "FavoriteViewController.h"
#import "LiveDailyNewsAppDelegate.h"
#import "LiveDailyNews.h"
#import "CustomCell.h"
#import "WebViewController.h"


@implementation FavoriteViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tabBarItem.title = @"收藏";
		self.tabBarItem.image = [UIImage imageNamed:@"TAB_ICON_CHAT.png"];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}






#pragma mark - View lifecycle
- (void)viewDidLoad
{
    //获取整个手机屏幕
    UIView *contentView = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
	
	contentView.autoresizesSubviews = YES;
	self.view = contentView;
	[self.view setBackgroundColor:[UIColor clearColor]];
   	
	mtableView = [[UITableView alloc] initWithFrame:
                  CGRectMake(0, 0, contentView.bounds.size.width, contentView.bounds.size.height - 44 - 48) style:UITableViewCellStyleDefault];
	mtableView.delegate = self;
	mtableView.dataSource = self;
	mtableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	mtableView.scrollEnabled = YES;
	[mtableView setBackgroundColor:[UIColor clearColor]];
    
	[self.view addSubview:mtableView];
    
    //收藏标题
    self.navigationItem.title = @"收藏";
    
    //删除按钮
    UIBarButtonItem *moveButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"编辑"
                                   style:UIBarButtonItemStyleBordered
                                   target:self 
                                   action:@selector(toggleMove)];
    self.navigationItem.rightBarButtonItem = moveButton;
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}


- (void)viewWillAppear:(BOOL)animated
{
    sectionName = nil;
    sectionArray = nil;
    category = nil;
    
//    sectionName = [NSMutableArray array];
    sectionName = [[NSMutableArray alloc] initWithObjects: nil];
    sectionArray = [[NSMutableArray alloc] initWithObjects: nil];
    //定义类别
    category = [[NSArray alloc] 
                initWithObjects:@"娱乐新闻", @"国内新闻", nil];
    NSError *error;
    liveDelegate = [[UIApplication sharedApplication] delegate];
    context = [liveDelegate managedObjectContext];
    entityDescription = [NSEntityDescription
                         entityForName:@"LiveDailyNews"
                         inManagedObjectContext:context];
    request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    
    for (NSString *categoryName in category) {
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"(category = %@)",categoryName];
        [request setPredicate:pred];
        NSMutableArray *sectionTemp = [[NSMutableArray alloc] initWithArray: [context executeFetchRequest:request error:&error]];
        if ([sectionTemp count] > 0) {
            [sectionArray addObject:sectionTemp];
            [sectionName addObject:categoryName];
        }
        sectionTemp = nil;
    }

    [mtableView reloadData];

}

//数据库查询



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



//删除处理
-(void)toggleMove
{
    [mtableView setEditing:!mtableView.editing animated:YES];
    if (mtableView.editing) {
        [self.navigationItem.rightBarButtonItem setTitle:@"取消"];
    } else {
        [self.navigationItem.rightBarButtonItem setTitle:@"编辑"];
    }
}

#pragma mark -
//在tableview中有多少个分组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [sectionName count];
}

//在当前分组中有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[sectionArray objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"cell");
    static NSString *favoriteIdentifier = @"FavoriteIdentifier";
    CustomCell *cell = (CustomCell *)[tableView
                                      dequeueReusableCellWithIdentifier:favoriteIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" 
                                                     owner:self
                                                   options:nil];
        for (id oneObject in nib) {
            if ([oneObject isKindOfClass:[CustomCell class]]) {
                cell = (CustomCell *)oneObject;
            }
        }
    }
    NSUInteger sectionNum = [indexPath section];
    NSUInteger row = [indexPath row];
    
    cell.titleLabel.text = [[[sectionArray objectAtIndex:sectionNum] objectAtIndex:row] valueForKey:@"title"];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[[sectionArray objectAtIndex:sectionNum] objectAtIndex:row] valueForKey:@"imagePath"]];
    cell.itemImageView.image = image;
    cell.descripLabel.text = [[[sectionArray objectAtIndex:sectionNum] objectAtIndex:row] valueForKey:@"descrip"];
                      
    return cell;
}
//获取分组标题并显示
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [sectionName objectAtIndex:section];
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return false;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 70;
}

////////////删除
//用户完成一项编辑(删除或插入)操作时,表视图将调用此方法
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NSError *error;
    NSUInteger row = [indexPath row];
    NSUInteger sectionNum = [indexPath section];
    
    //删除本地图片
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    BOOL boolRemove = [defaultManager removeItemAtPath:
                       [[[sectionArray objectAtIndex:sectionNum] objectAtIndex:row] valueForKey:@"imagePath"]  error:nil];
    if (!boolRemove) {
        NSLog(@"remove cover image fail");
    }
    
    
    
   
    
    
    [context deleteObject:[[sectionArray objectAtIndex:sectionNum] objectAtIndex:row]];
    if (![context save:&error]) {
        NSLog(@"Error删除保存 %@",[error localizedDescription]);
    }
    
    [mtableView beginUpdates];
    if ([[sectionArray objectAtIndex:sectionNum] count] <= 1) {
        [sectionArray removeObjectAtIndex:sectionNum];
        [sectionName removeObjectAtIndex:sectionNum];
        [mtableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                          withRowAnimation:UITableViewRowAnimationFade];
        [mtableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] 
                  withRowAnimation:UITableViewRowAnimationFade];
    } else {
        [[sectionArray objectAtIndex:sectionNum] removeObjectAtIndex:row];
        [mtableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                          withRowAnimation:UITableViewRowAnimationFade];
    }
    [mtableView endUpdates];
   
    [mtableView reloadData];
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  @"确认删除";
}


//点击查看
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger sectionNum = [indexPath section];
    NSUInteger row = [indexPath row];
    NSManagedObject *object = [[sectionArray objectAtIndex:sectionNum] objectAtIndex:row];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[object valueForKey:@"title"] forKey:@"title"];
    [userDefaults setObject:[object valueForKey:@"link"] forKey:@"link"];
    [userDefaults setObject:[object valueForKey:@"content"] forKey:@"content"];
    [userDefaults setObject:[object valueForKey:@"imagePath"] forKey:@"imagePath"];
    [userDefaults setObject:[object valueForKey:@"pubDate"] forKey:@"pubDate"];
    [userDefaults setObject:[object valueForKey:@"category"] forKey:@"category"];
    [userDefaults setObject:[object valueForKey:@"descrip"] forKey:@"description"];
    WebViewController *webView = [[WebViewController alloc] init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webView animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

@end
